import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

// 性能指标收集器
class PerformanceMetricsCollector {
  constructor(options = {}) {
    this.metrics = reactive({
      // 页面加载性能
      pageLoad: {
        firstPaint: 0,
        firstContentfulPaint: 0,
        domContentLoaded: 0,
        load: 0
      },
      // API 调用性能
      apiCalls: {
        total: 0,
        success: 0,
        failed: 0,
        avgResponseTime: 0,
        slowCalls: 0
      },
      // 资源加载性能
      resources: {
        total: 0,
        loaded: 0,
        failed: 0,
        avgLoadTime: 0
      },
      // 内存使用
      memory: {
        usedJSHeapSize: 0,
        totalJSHeapSize: 0,
        jsHeapSizeLimit: 0
      },
      // 帧率
      fps: {
        current: 0,
        min: 0,
        max: 0,
        avg: 0
      }
    })

    this.history = reactive({
      apiCalls: [],
      resources: [],
      memory: [],
      fps: []
    })

    this.options = {
      maxHistorySize: options.maxHistorySize || 1000,
      collectInterval: options.collectInterval || 5000,
      fpsThreshold: options.fpsThreshold || 30,
      slowApiThreshold: options.slowApiThreshold || 1000
    }

    this.timers = new Map()
    this.observers = new Map()
  }

  // 初始化性能指标收集
  init() {
    this.collectPageLoadMetrics()
    this.startMemoryCollection()
    this.startFPSCollection()
    this.setupResourceObserver()
    this.setupApiInterceptor()
  }

  // 收集页面加载性能指标
  collectPageLoadMetrics() {
    const timing = performance.timing
    if (timing) {
      this.metrics.pageLoad = {
        firstPaint: performance.getEntriesByType('paint')
          .find(entry => entry.name === 'first-paint')?.startTime || 0,
        firstContentfulPaint: performance.getEntriesByType('paint')
          .find(entry => entry.name === 'first-contentful-paint')?.startTime || 0,
        domContentLoaded: timing.domContentLoadedEventEnd - timing.navigationStart,
        load: timing.loadEventEnd - timing.navigationStart
      }
    }
  }

  // 开始内存使用收集
  startMemoryCollection() {
    const collectMemory = () => {
      if (performance.memory) {
        const memory = performance.memory
        this.metrics.memory = {
          usedJSHeapSize: memory.usedJSHeapSize,
          totalJSHeapSize: memory.totalJSHeapSize,
          jsHeapSizeLimit: memory.jsHeapSizeLimit
        }
        this.addToHistory('memory', { ...this.metrics.memory, timestamp: Date.now() })
      }
    }

    this.timers.set('memory', setInterval(collectMemory, this.options.collectInterval))
  }

  // 开始帧率收集
  startFPSCollection() {
    let frameCount = 0
    let lastTime = performance.now()
    let frames = []

    const calculateFPS = () => {
      const now = performance.now()
      const elapsed = now - lastTime
      frameCount++

      if (elapsed >= 1000) {
        const fps = Math.round((frameCount * 1000) / elapsed)
        frames.push(fps)
        if (frames.length > 60) frames.shift()

        this.metrics.fps = {
          current: fps,
          min: Math.min(...frames),
          max: Math.max(...frames),
          avg: Math.round(frames.reduce((a, b) => a + b, 0) / frames.length)
        }

        this.addToHistory('fps', { ...this.metrics.fps, timestamp: Date.now() })
        
        frameCount = 0
        lastTime = now
      }

      requestAnimationFrame(calculateFPS)
    }

    requestAnimationFrame(calculateFPS)
  }

  // 设置资源加载观察器
  setupResourceObserver() {
    const observer = new PerformanceObserver((list) => {
      list.getEntries().forEach(entry => {
        if (entry.entryType === 'resource') {
          this.metrics.resources.total++
          if (entry.duration > 0) {
            this.metrics.resources.loaded++
            this.metrics.resources.avgLoadTime = 
              (this.metrics.resources.avgLoadTime * (this.metrics.resources.loaded - 1) + entry.duration) / 
              this.metrics.resources.loaded
          } else {
            this.metrics.resources.failed++
          }

          this.addToHistory('resources', {
            name: entry.name,
            duration: entry.duration,
            timestamp: Date.now()
          })
        }
      })
    })

    observer.observe({ entryTypes: ['resource'] })
    this.observers.set('resource', observer)
  }

  // 设置 API 调用拦截器
  setupApiInterceptor() {
    const originalFetch = window.fetch
    window.fetch = async (...args) => {
      const startTime = performance.now()
      this.metrics.apiCalls.total++

      try {
        const response = await originalFetch(...args)
        const endTime = performance.now()
        const duration = endTime - startTime

        if (response.ok) {
          this.metrics.apiCalls.success++
        } else {
          this.metrics.apiCalls.failed++
        }

        this.metrics.apiCalls.avgResponseTime = 
          (this.metrics.apiCalls.avgResponseTime * (this.metrics.apiCalls.success + this.metrics.apiCalls.failed - 1) + duration) / 
          (this.metrics.apiCalls.success + this.metrics.apiCalls.failed)

        if (duration > this.options.slowApiThreshold) {
          this.metrics.apiCalls.slowCalls++
        }

        this.addToHistory('apiCalls', {
          url: args[0],
          method: args[1]?.method || 'GET',
          duration,
          status: response.status,
          timestamp: Date.now()
        })

        return response
      } catch (error) {
        this.metrics.apiCalls.failed++
        throw error
      }
    }
  }

  // 添加历史记录
  addToHistory(type, data) {
    this.history[type].push(data)
    if (this.history[type].length > this.options.maxHistorySize) {
      this.history[type].shift()
    }
  }

  // 生成性能报告
  generateReport() {
    const report = {
      timestamp: new Date().toISOString(),
      summary: {
        pageLoad: { ...this.metrics.pageLoad },
        apiCalls: { ...this.metrics.apiCalls },
        resources: { ...this.metrics.resources },
        memory: { ...this.metrics.memory },
        fps: { ...this.metrics.fps }
      },
      analysis: this.analyzeMetrics(),
      recommendations: this.generateRecommendations()
    }

    return report
  }

  // 分析性能指标
  analyzeMetrics() {
    const analysis = {
      performance: {
        score: 0,
        issues: []
      },
      api: {
        score: 0,
        issues: []
      },
      resources: {
        score: 0,
        issues: []
      },
      memory: {
        score: 0,
        issues: []
      }
    }

    // 分析页面加载性能
    if (this.metrics.pageLoad.firstContentfulPaint > 2000) {
      analysis.performance.issues.push('首次内容绘制时间过长')
    }
    if (this.metrics.pageLoad.load > 3000) {
      analysis.performance.issues.push('页面完全加载时间过长')
    }

    // 分析 API 调用性能
    const apiSuccessRate = this.metrics.apiCalls.success / this.metrics.apiCalls.total
    if (apiSuccessRate < 0.95) {
      analysis.api.issues.push('API 调用成功率较低')
    }
    if (this.metrics.apiCalls.avgResponseTime > 500) {
      analysis.api.issues.push('API 平均响应时间过长')
    }
    if (this.metrics.apiCalls.slowCalls > 0) {
      analysis.api.issues.push(`存在 ${this.metrics.apiCalls.slowCalls} 个慢调用`)
    }

    // 分析资源加载性能
    const resourceSuccessRate = this.metrics.resources.loaded / this.metrics.resources.total
    if (resourceSuccessRate < 0.95) {
      analysis.resources.issues.push('资源加载成功率较低')
    }
    if (this.metrics.resources.avgLoadTime > 1000) {
      analysis.resources.issues.push('资源平均加载时间过长')
    }

    // 分析内存使用
    const memoryUsage = this.metrics.memory.usedJSHeapSize / this.metrics.memory.jsHeapSizeLimit
    if (memoryUsage > 0.8) {
      analysis.memory.issues.push('内存使用率过高')
    }

    // 计算各项得分
    analysis.performance.score = this.calculateScore(analysis.performance.issues)
    analysis.api.score = this.calculateScore(analysis.api.issues)
    analysis.resources.score = this.calculateScore(analysis.resources.issues)
    analysis.memory.score = this.calculateScore(analysis.memory.issues)

    return analysis
  }

  // 生成优化建议
  generateRecommendations() {
    const recommendations = []
    const analysis = this.analyzeMetrics()

    // 根据分析结果生成建议
    if (analysis.performance.issues.length > 0) {
      recommendations.push({
        type: 'performance',
        priority: 'high',
        title: '页面加载性能优化',
        description: '建议优化以下方面：\n' + analysis.performance.issues.join('\n'),
        impact: 80
      })
    }

    if (analysis.api.issues.length > 0) {
      recommendations.push({
        type: 'api',
        priority: 'medium',
        title: 'API 调用优化',
        description: '建议优化以下方面：\n' + analysis.api.issues.join('\n'),
        impact: 70
      })
    }

    if (analysis.resources.issues.length > 0) {
      recommendations.push({
        type: 'resources',
        priority: 'medium',
        title: '资源加载优化',
        description: '建议优化以下方面：\n' + analysis.resources.issues.join('\n'),
        impact: 60
      })
    }

    if (analysis.memory.issues.length > 0) {
      recommendations.push({
        type: 'memory',
        priority: 'high',
        title: '内存使用优化',
        description: '建议优化以下方面：\n' + analysis.memory.issues.join('\n'),
        impact: 90
      })
    }

    return recommendations
  }

  // 计算性能得分
  calculateScore(issues) {
    const baseScore = 100
    const deductionPerIssue = 20
    return Math.max(0, baseScore - issues.length * deductionPerIssue)
  }

  // 清理资源
  cleanup() {
    // 清理定时器
    this.timers.forEach(timer => clearInterval(timer))
    this.timers.clear()

    // 清理观察器
    this.observers.forEach(observer => observer.disconnect())
    this.observers.clear()

    // 恢复原始 fetch
    if (window.fetch.__originalFetch) {
      window.fetch = window.fetch.__originalFetch
    }
  }
}

// 导出性能指标收集器实例
export const metricsCollector = new PerformanceMetricsCollector()

// 导出工具函数
export function usePerformanceMetrics() {
  const isCollecting = ref(false)

  // 开始收集性能指标
  const startCollection = () => {
    if (!isCollecting.value) {
      metricsCollector.init()
      isCollecting.value = true
    }
  }

  // 停止收集性能指标
  const stopCollection = () => {
    if (isCollecting.value) {
      metricsCollector.cleanup()
      isCollecting.value = false
    }
  }

  // 获取当前性能指标
  const getMetrics = () => {
    return metricsCollector.metrics
  }

  // 获取历史记录
  const getHistory = () => {
    return metricsCollector.history
  }

  // 生成性能报告
  const generateReport = () => {
    return metricsCollector.generateReport()
  }

  return {
    isCollecting,
    startCollection,
    stopCollection,
    getMetrics,
    getHistory,
    generateReport
  }
} 